const router = require('koa-router')()
const util = require('../utils/util')
const Dept = require('../models/deptSchema')

router.prefix('/dept')

router.post('/init', (ctx) => {
  for (var i = 0; i < 3; i++) {
    const params = {
      deptName: `测试${i}`,
      userId: '3',
      userEmail: '123@imooc.com',
    }
    Dept.create(params)
  }

  ctx.body = util.success('初始化成功')
})

router.get('/allList', async (ctx) => {
  try {
    const list = await Dept.find()
    const permissionList = getTreeDept(list, undefined, [])
    ctx.body = util.success({
      list: permissionList,
    })
  } catch (error) {
    ctx.body = util.fail(error.stack)
  }
})

router.get('/list', async (ctx) => {
  const { deptName } = ctx.request.query
  const { page, skipIndex } = util.pager(ctx.request.query)
  let params = {}
  if (deptName) params.deptName = deptName

  try {
    const query = Dept.find(params)
    const list = await query.skip(skipIndex).limit(page.pageSize)
    const total = await Dept.countDocuments(params)

    const permissionList = getTreeDept(list, undefined, [])
    ctx.body = util.success({
      list: permissionList,
      page: {
        ...page,
        total,
      },
    })
  } catch (error) {
    ctx.body = util.fail(error.stack)
  }
})

// 递归拼接树形列表
function getTreeDept(rootList, id, list) {
  for (let i = 0; i < rootList.length; i++) {
    let item = rootList[i]

    if (String(item.parentId[0]) == String(id)) {
      list.push(item._doc)
    }
  }

  list.map((item) => {
    item.children = []
    getTreeDept(rootList, item._id, item.children)
    if (item.children.length == 0) {
      delete item.children
    } else if (item.children.length > 0 && item.children[0].menuType == 2) {
      // 快速区分按钮和菜单，用于后期做菜单按钮权限控制
      item.action = item.children
    }
  })
  return list
}

router.post('/operate', async (ctx) => {
  const { _id, action, ...params } = ctx.request.body
  let res, info
  // console.log(params, 'params')
  try {
    if (action == 'add') {
      res = await Dept.create(params)
      info = '创建成功'
    } else if (action == 'edit') {
      params.updateTime = new Date()
      console.log(_id, 'params')
      res = await Dept.findByIdAndUpdate(_id, params)
      info = '编辑成功'
    } else {
      res = await Dept.findByIdAndRemove(_id)
      info = '删除成功'
    }
    ctx.body = util.success('', info)
  } catch (error) {
    ctx.body = util.fail(error.stack)
  }
})
module.exports = router
